﻿/***************************************************
Copyright (C) 2012 Alexander Forselius

Permission is hereby granted, free of charge, to any person obtaining a copy of this 
software and associated documentation files (the "Software"), to deal in the Software
 without restriction, including without limitation the rights to use, copy, modify, merge,
 publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons 
 to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace Bungalow
{
        public class IBungalowResources : CefSharp.ISchemeHandler
        {

            public bool ProcessRequest(CefSharp.IRequest request, ref string mimeType, ref System.IO.Stream stream)
            {
             //   if (request.Url.StartsWith("spotify:") || request.Url.StartsWith("bungalow:"))
            //    {
               //     Program.Shell.Navigate(new Uri(request.Url));
                 //   return false;
              //  }
                if (request.Url.StartsWith(Program.BUNGALOW_PROTOCOL) || request.Url.ToString().StartsWith("sp://") || !request.Url.ToString().Contains("://"))
                {
                    FileInfo fi = null;

                    String folder = Properties.Settings.Default.ResDir +"\\apps\\";
                    String path = folder  + request.Url.Replace(Program.BUNGALOW_PROTOCOL, "").Replace("sp://", "").Replace("/", "\\");
                    if (File.Exists(path))
                    {
                        fi = new FileInfo(path);

                         
                    }
                    else
                    {
                        folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Bungalow\\";

                        path = folder + request.Url.Replace(Program.BUNGALOW_PROTOCOL, "").Replace("sp://", "").Replace("/", "\\");
                        fi = new FileInfo(path);
                    }

                    if (fi != null)
                    {
                        switch (fi.Extension)
                        {

                            case ".txt":
                                mimeType = "text/plain";
                                break;
                            case ".js":
                                mimeType = "application/javascript";
                                break;
                            case ".css":
                                mimeType = "text/css";
                                break;
                            case ".xhtml":
                                mimeType = "application/xml+xhtml";
                                break;
                            case ".html":
                                mimeType = "text/html";
                                break;
                            case ".png":
                                mimeType = "image/png";
                                break;
                            case ".jpeg":
                            case ".jpg":
                                mimeType = "image/jpg";
                                break;
                        }
                        String contents = "";
                        try
                        {
                            if (mimeType.StartsWith("text/")||mimeType.StartsWith("application/"))
                            {
                                using (StreamReader sr = new StreamReader(fi.FullName))
                                {
                                    contents = sr.ReadToEnd();

                                }
                                byte[] bytes = Encoding.UTF8.GetBytes(contents);
                                stream = new MemoryStream(bytes);
                            }
                            else if (mimeType.StartsWith("image/"))
                            {
                            System.Drawing.Image image = System.Drawing.Image.FromFile(fi.FullName);
                                MemoryStream ms = new MemoryStream();
                                switch (mimeType)
                                {

                                    case "image/png":
                                        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                                        break;
                                    case "image/jpg":
                                    case "image/jpeg":
                                        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                                        break;
                                }
                                stream = ms;
                            }
                        }
                        catch (Exception e)
                        {
                            return false;
                        }

                    }
                    return true;
                }
                else
                {

                    return false;
                }
            }
        }
        public class IBungalowHandlerFactory : CefSharp.ISchemeHandlerFactory
        {

            public CefSharp.ISchemeHandler Create()
            {
                return new IBungalowResources();

            }
        }
        public class AppState
        {

            public String subscriptionTitle { get; set; }
            public String GetSubscriptionTitle() { return subscriptionTitle; }
            public void SetSubscriptionTitle(String val)
            {
                this.subscriptionTitle = val;
            }
        }
    public static class Program
    {
        public static AppState appState = new AppState();
        public static String BUNGALOW_PROTOCOL = "bl://";
        public static Bungalow Shell;
        public static DefaultSkin Skin;
        public static Dictionary<String, String> Handlers = new Dictionary<string, string>();
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            CefSharp.Settings settings = new CefSharp.Settings();
            Handlers.Add("isbn", "bungalow:app:books:{$value}#{$action}");
            CefSharp.Example.ExamplePresenter.Init();
            CefSharp.CEF.Initialize(settings);
            CefSharp.CEF.RegisterScheme("bl", new IBungalowHandlerFactory());
            CefSharp.CEF.RegisterScheme("sp", new IBungalowHandlerFactory());
            CefSharp.CEF.RegisterJsObject("__appState", Program.appState); 
            Skin = new DefaultSkin();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Shell = new Bungalow();
            Application.Run(Shell);
        }
    }
}
